package com.kili.picture.tools;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.kili.picture.context.SpringContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author Jar
 * @Date 2019/3/27
 */
public class OSSClientUtils {

    private static final Logger logger = LoggerFactory.getLogger(OSSClientUtils.class);

    private static String endpoint;
    private static String accessId;
    private static String accessSecret;
    private static String bucketName;

    private static OSSClient ossClient;

    static {
        Environment environment = SpringContext.getApplicationContext().getEnvironment();
        endpoint = environment.getProperty("oss.endpoint", String.class);
        accessId = environment.getProperty("oss.access.key.id", String.class);
        accessSecret = environment.getProperty("oss.access.key.secret", String.class);
        bucketName = environment.getProperty("oss.bucket.name", String.class);

        ossClient = new OSSClient(endpoint, accessId, accessSecret);
    }

    public static void uploadObject2OSS(MultipartFile file, String path) {
        InputStream inputStream = null;

        try {
            inputStream = file.getInputStream();
            uploadObject2OSS(inputStream, path, file.getOriginalFilename(), file.getSize());
        } catch (Exception e) {
            throw new RuntimeException("upload to oss error");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void uploadObject2OSS(File file, String path) {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            uploadObject2OSS(inputStream, path, file.getName(), file.length());
        } catch (Exception e) {
            throw new RuntimeException("upload to oss error");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void uploadObject2OSS(InputStream inputStream, String path, String fileName, Long fileSize) throws Exception {
        OSSClient ossClient = getOSSClient();

        String filePath = path.substring(0, path.lastIndexOf("/") + 1);

        if (!ossClient.doesObjectExist(bucketName, filePath)) {
            // 创建文件夹
            ossClient.putObject(bucketName, filePath, new ByteArrayInputStream(new byte[0]));
        }

        // 创建上传Object的Metadata
        ObjectMetadata metadata = new ObjectMetadata();
        // 上传的文件的长度
        metadata.setContentLength(inputStream.available());
        // 指定该Object被下载时的网页的缓存行为
        metadata.setCacheControl("no-cache");
        // 指定该Object下设置Header
        metadata.setHeader("Pragma", "no-cache");
        // 指定该Object被下载时的内容编码格式
        metadata.setContentEncoding("utf-8");
        // 文件的MIME,定义文件的类型及网页编码,决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成,
        // 如果没有扩展名则填默认值application/octet-stream
        metadata.setContentType(getContentType(fileName));
        // 指定该Object被下载时的名称(指示MINME用户代理如何显示附加的文件,打开或下载,及文件名称)
        metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");

        // 上传文件 (上传文件流的形式)
        PutObjectResult putResult = ossClient.putObject(bucketName, path, inputStream, metadata);

        logger.info("put result:", putResult.getResponse());
    }

    public static boolean deleteObject(String path) {
        OSSClient ossClient = getOSSClient();
        ossClient.deleteObject(bucketName, path);
        return true;
    }

    /**
     * 获取阿里云OSS客户端对象
     *
     * @return ossClient
     */
    private static OSSClient getOSSClient() {
        return ossClient;
    }

    /**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     *
     * @param fileName
     * @return 文件的contentType
     */
    private static String getContentType(String fileName) {
        // 文件的后缀名
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if (".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)
                || ".png".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        }
        if (".html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        // 默认返回类型
        return "image/jpeg";
    }

}
